#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HeilongjiangJixiPolicy(BaseTaxPolicySpider):
    name = 'heilongjiang_jixi2_policy'
    
    province = '黑龙江省'
    city: str = "鸡西市"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格
    custom_settings = {"DOWNLOAD_TIMEOUT": 60}

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        new_settings = {
            **(cls.custom_settings or {}),
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url, path in [
            ['鸡西市滴道区人民政府', "滴道区", "http://www.didaoqu.gov.cn/ddq/528397444d3b4b8ba4e031b996413571/zfxxgk.shtml", "首页>政府信息公开>政策>行政规范文件"],
            ['鸡西市滴道区人民政府', "滴道区", "http://www.didaoqu.gov.cn/ddq/528397444d3b4b8ba4e031b996413571/zfxxgk.shtml", "首页>政府信息公开>政策>其他文件>政发文件"],
            ['鸡西市滴道区人民政府', "滴道区", "http://www.didaoqu.gov.cn/ddq/528397444d3b4b8ba4e031b996413571/zfxxgk.shtml", "首页>政府信息公开>政策>其他文件>政办发文件"],
            ['鸡西市梨树区人民政府', "梨树区", "http://jixilishu.gov.cn/lsq/4b00c61b047649e2956848ef1b9ef889/zfxxgk.shtml", "首页>政府信息公开>政策>行政规范文件"],
            ['鸡西市梨树区人民政府', "梨树区", "http://jixilishu.gov.cn/lsq/4b00c61b047649e2956848ef1b9ef889/zfxxgk.shtml", "首页>政府信息公开>政策>其他文件>政发文件"],
            ['鸡西市梨树区人民政府', "梨树区", "http://jixilishu.gov.cn/lsq/4b00c61b047649e2956848ef1b9ef889/zfxxgk.shtml", "首页>政府信息公开>政策>其他文件>政办发文件"],
            ['鸡西市城子河区人民政府', "城子河区", "http://www.czh.gov.cn/czh/0e7c630ae12d461ca46843b4015a23c5/zfxxgk.shtml", "首页>政府信息公开>政策>行政规范文件"],
            ['鸡西市城子河区人民政府', "城子河区", "http://www.czh.gov.cn/czh/0e7c630ae12d461ca46843b4015a23c5/zfxxgk.shtml", "首页>政府信息公开>政策>其他文件>政发文件"],
            ['鸡西市城子河区人民政府', "城子河区", "http://www.czh.gov.cn/czh/0e7c630ae12d461ca46843b4015a23c5/zfxxgk.shtml", "首页>政府信息公开>政策>其他文件>政办发文件"],
        ]:
            item = {'source': source, 'county': county}
            meta = {'item': item, 'path': path}
            name, code = url.split(".gov.cn/")[-1].split("/")[:2]
            # if 'c10' in code:
            meta['name'] = name
            #     meta['code'] = code
            yield scrapy.Request(url, callback=self.parse_js, meta=meta, dont_filter=True)

    def parse_js(self, response, **kwargs):
        meta = response.meta
        name = response.xpath("//meta[@name='websiteCode']/@content").get() or meta['name']
        js = response.url.split("/")[-1].split(".")[0]
        url = response.xpath(f"""//script[contains(@src, "{js.replace('_', '')}.js")]/@src""").get()
        if not url:
            url = response.xpath('//script[not(contains(@src, "_")) and contains(@src, "zfxxgk")]/@src').getall()[-1]
        meta['name'] = name
        yield response.follow(url, callback=self.parse_id, meta=meta, dont_filter=True)

    def parse_id(self, response, **kwargs):
        meta = response.meta
        if '.js' in response.url:
            channel_list_api = response.xpath(""".""").re_first(r"[Uu]+rl\s*[\+:]+\s*'(.*getChannelList.*)\?")
            search_api = response.xpath(""".""").re_first(r"[Uu]+rl\s*[\+:]+\s*'(.*search/)'")
            meta['channel_list_api'] = channel_list_api
            meta['search_api'] = search_api
        code = meta.get('code') or response.xpath(""".""").re_first(r"requestCode\('(.*)'\);") or response.xpath(""".""").re_first(r"renderLeftMenu\('(.*)'\);")
        name = meta['name']
        channel_list_api = meta.get('channel_list_api') or '/getChannelList'
        url = f'{channel_list_api}?channelCode={code}&websiteCodeName={name}'
        yield response.follow(url, callback=self.parse_content, meta=meta, dont_filter=True)

    def parse_content(self, response, **kwargs):
        print(response.url)
        meta = response.meta
        channelName = meta['path'].split('>')[-3]
        for children in response.json()['results'].get('children', []):
            if channelName == children['channelName']:
                response.meta['code'] = children['channelCode']
                yield from self.parse_id(response)
                return
        channelName = meta['path'].split('>')[-2]
        data = response.json()['results']
        for children in response.json()['results'].get('children', []):
            if channelName == children['channelName']:
                response.meta['code'] = children['channelCode']
                yield from self.parse_id(response)
                return
        channelName = meta['path'].split('>')[-1]
        for children in response.json()['results'].get('children', []):
            if channelName == children['channelName']:
                data = children
                break
        # for children in response.json()['results'].get('channelLevel', []):
        #     if channelName == children['channelName']:
        #         data = children
        #         break
        print(meta['code'], meta['name'], channelName, data['channelName'], "GETSAME" if channelName == data['channelName'] else "DIFF")
        if channelName == data['channelName']:
            search_api = meta.get("search_api") or '/search/'
            channelId = data['channelId']
            params = {
                "sort": "",
                "_isAgg": "true",
                "_isJson": "true",
                "_pageSize": "20",
                "_template": "index",
                "_rangeTimeGte": "",
                "_rangeTimeLt": "",
                "_channelName": "",
                "page": "1"
            }
            url = search_api + channelId + '?'
            meta['params'] = params
            meta['url'] = url
            yield response.follow(url + urlencode(params), callback=self.parse_list, meta=meta)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        datas = response.json()['data']

        for elem in datas['results']:
            item = Item()
            item['source_url'] = elem['url']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['publishedTimeStr'].split(" ")[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            # print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False and self.get_next == '0':
            total = datas['total']
            total_page = math.ceil(total / 20)
            print(meta['code'], meta['name'], response.url, total, "page:", total_page)
            for page_num in range(1, int(total_page) + 2):
                url = meta['url']
                params = meta['params']
                params['page'] = str(page_num)
                yield response.follow(url + urlencode(params), callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl heilongjiang_jixi2_policy -a get_next=0".split())
